function [pX,pY,ODraw] = ProcessImageGUI(handles)

% [pX,pY,OD] = ProcessImage(hdfFilePath,autoROI,userROI,doFitData)
% Finds Gaussian-shaped signals on fluorescence or absorption images.
% Returns:
% pX - The parameters for a Gaussian fit to the data in the x (vertical)
% direction.
% pX(1) = Gaussian amplitude
% pX(2) = Peak position (in units of image pixels)
% pX(3) = Standard deviation (in units of image pixels)
% pX(4) = Offset
% pY - Same description as pX
% OD - The image (OD if it's an absorption image, raw image for a fluor.)
% num - Counts in raw "atoms" image, with electronic noise subtracted
% den - Counts in raw "background" image, with electronic noise subtracted.

fit2d = handles.do2DFit;
hdfFilePath = handles.dpath;
autoROI = handles.autoROI;
doFitData = handles.do1DFit;
userROI = handles.ROI;
useBackground = handles.useBackground;
scaleBackground = handles.scaleBackground;

% Inputs from hdf5 file
rawimages = cast(h5read(hdfFilePath,'/Image/image'),'double')/4; % Divide by 4 as 14-bit data from camera is multiplied by 4 (presumably when cast as a 16-bit integer).
img_var = h5read(hdfFilePath,'/Image/configuration');
img_time = h5read(hdfFilePath,'/Image/exposuretime');
type_img = h5read(hdfFilePath,'/Image/typeimaging');
CCDbin = 1; % Amount of binning at camera sensor; '1' is 1x1 binning and '2' is 2x2 binning

%Software binning for 2D fits
bindim=[4,4];  % Software binning size

% Libraries used in this function
expp = ParamImgSys(img_var);
cons = Constants();

% Size of hdf5 image group
[rows,cols,files] = size(rawimages); % rows = horiz. pixels; cols = vert. pixels

%%% TODO: Check validity of image, has pixels, correct size, has been
%%% binned etc.
if rows*cols == 0
    error('No image in HDF file (returned empty matrix)')
end

ovflw = 'no';   % setting 'ovflw' flag to 'no'
if  type_img == 3 % Absorption
    if useBackground
        elec = rawimages(:,:,3);
    else
        elec = 0;
    end
    
    if scaleBackground
        sampleIndX = 1192:1392;
        sampleIndY = 1:200;
        scaleS = mean(mean(rawimages(sampleIndX,sampleIndY,1)));
        scaleB = mean(mean(rawimages(sampleIndX,sampleIndY,2)));
    else
        scaleS = 1;
        scaleB = 1;
    end
    
    num = rawimages(:,:,1) - elec;
    den = rawimages(:,:,2)*scaleS/scaleB - elec;
    
    maxcntN = max(max(num));
    maxcntD = max(max(den));
    if maxcntN > 2^16 || maxcntD > 2^16
        ovflw = 'yes';
        warning('Bin overflow warning');
    end
    
    %scaling the baselevel of the atom image
    numforscale=10;  %using a 10x10 pixel area to determine scaling fraction
    numleftup = sum(sum(num(1:numforscale,1:numforscale)));
    numleftdn = sum(sum(num(rows-numforscale:rows,1:numforscale)));
    numrightup = sum(sum(num(1:numforscale,cols-numforscale:cols)));
    numrightdn = sum(sum(num(rows-numforscale:rows,cols-numforscale:cols)));
    baselevelnum = numleftup + numleftdn + numrightup + numrightdn;
    
    denleftup = sum(sum(den(1:numforscale,1:numforscale)));
    denleftdn = sum(sum(den(rows-numforscale:rows,1:numforscale)));
    denrightup = sum(sum(den(1:numforscale,cols-numforscale:cols)));
    denrightdn = sum(sum(den(rows-numforscale:rows,cols-numforscale:cols)));
    baselevelden = denleftup + denleftdn + denrightup + denrightdn;
    blscale = (baselevelden/baselevelnum); %resulting baselevel scaling
    modnum=num*blscale;
    
    den(den==0) = 1; % Remove zeros from denominator
    
    ODraw = -log((num./den)');  % MATRIX ROTATED HERE
    ODrawmod = -log(modnum./den);
    ODraw(isinf(ODraw)) = 0;
    ODraw(isnan(ODraw)) = 0;
    ODraw = real(ODraw);
    
elseif type_img == 1 % Fluorescence
    ODraw = rawimages';         % MATRIX ROTATED HERE
    ODraw = ODraw - min(min(ODraw));
else
    error('Can''t determine imaging method');
end

% Filter image to find ROI
N = 30;  %amplitude of 2D gaussian filter
sig = 60;  %size of 2D gaussian filter
ODfilt = conv2(ODraw,gaussian2d(N,sig),'same'); % Low-pass filter image

yC = 1:expp.short_px_nb;   %HORIZONTAL DIMENSION OF EXPERIMENT
xC = 1:expp.long_px_nb;

autoROIok = false;

if autoROI % Find ROI and extract first approx. signal from filtered image
    % Determine pre-ROI for fitting (for initial guesses)
    mx = max(max(ODfilt));
    [I,J] = find(ODfilt == mx,1);
    wndw = 50;
    if ~(I - wndw < 1 || I + wndw > max(xC) || J - wndw < 1 || J + wndw > max(yC))
        autoROIok = true;
        
        ROI(1) = I(1);
        ROI(2) = J(1);
        
        % INTEGRATED ODfilt in diff. dimens. using pre-ROI as size (for initial guesses)
        yIntFilt = sum(ODfilt(:,ROI(2)-wndw:ROI(2)+wndw),2);
        xIntFilt = sum(ODfilt(ROI(1)-wndw:ROI(1)+wndw,:),1);
        
        % Least-squares fit of INTEGRATED ODfilt (initial guesses)
        ampGuessY = max(yIntFilt) - min(yIntFilt);
        ampGuessX = max(xIntFilt) - min(xIntFilt);
        options = optimset('Display','off','TolFun',1e-16,'TolX',1e-16);
        pYtmp = fminsearch(@(p)FitGauss(p,yC,yIntFilt),[ampGuessY ROI(1) 100 min(yIntFilt)],options);
        pXtmp = fminsearch(@(p)FitGauss(p,xC,xIntFilt'),[ampGuessX ROI(2) 100 min(xIntFilt)],options);
        
        % Determining autoROI based on size of ODfilt (for real fit)
        sigmas = 3;
        xWndw = round(sigmas*pXtmp(3));
        yWndw = round(sigmas*pYtmp(3));
        xROI = ROI(2)-xWndw:ROI(2)+xWndw;
        yROI = ROI(1)-yWndw:ROI(1)+yWndw;
        
        % Remove parts of the ROI if it goes outside of the photo.
        if min(xROI) < 1
            xROI = xROI(xROI > 0);
        end
        if min(yROI) < 1
            yROI = yROI(yROI > 0);
        end
        
        if max(yROI) > expp.short_px_nb
            yROI = yROI(yROI < expp.short_px_nb + 1);
        end
        if max(xROI) > expp.long_px_nb
            xROI = xROI(xROI < expp.long_px_nb + 1);
        end
        
        % INTEGRATED ODraw in diff. dimens. using autoROI as size (for real fit)
        yInt = sum(ODraw(yROI,xROI),2);
        xInt = sum(ODraw(yROI,xROI),1);
        
    else
        warndlg('Can''t auto-choose ROI: Estimated signal close to edge of image')
        autoROIok = false;
    end
end

if ~autoROIok  % Use user-input ROI parameters to get initial fitting parameters
    % User-defined ROI
    yROI = userROI(3):userROI(4);
    xROI = userROI(1):userROI(2);
    
    % INTEGRATED ODraw in diff. dimens. using autoROI as size (for real fit)
    yInt = sum(ODraw(yROI,xROI),2);
    xInt = sum(ODraw(yROI,xROI),1);
    
    % Amp. and sizes (initial guesses)
    pYtmp(1) = max(yInt) - min(yInt);
    pXtmp(1) = max(xInt) - min(xInt);
    pYtmp(2:3) = [mean(userROI(3:4)) 150];
    pXtmp(2:3) = [mean(userROI(1:2)) 150];
end

if doFitData % Real fit of ODraw using initial guesses
    options = optimset('Display','off','TolFun',1e-16,'TolX',1e-16);
    pY = fminsearch(@(p)FitGauss(p,yROI,yInt),[pYtmp(1:3) min(yInt)],options);
    pX = fminsearch(@(p)FitGauss(p,xROI,xInt'),[pXtmp(1:3) min(xInt)],options);
else
    pY = zeros(1,4);
    pX = pY;
end

if doFitData
    if fit2d % if 2D fit has been done
        figure(100)
        subplot(2,3,1)
        surf(ODfilt,'Marker','.') %Plot filtered OD data
        cax=caxis;
        colorbar
        shading flat
        grid off
        title('Filtered ODraw')
        view(0,90);
        xlabel('vert')
        ylabel('horiz')
        
        % Binning ODraw for 2D fitting
        ODrawbin=BinImg2d(ODraw,bindim);  % NOTE - Rotated w/ respect to original image
        
        figure(100)
        subplot(2,3,4)
        surf(ODrawbin,'Marker','.') %Plot binned ODraw data
        cax=caxis;
        colorbar
        shading flat
        grid off
        title('Binned ODraw')
        view(0,90);
        xlabel('vert binned')
        ylabel('horiz binned')
        
        % Using ODrawbin for 2D fitting IC
        [horizbin,vertbin] = size(ODrawbin);  % y-dir. is HORIZ. exper. dir.; x-dir. is VERT
        amp2d=max(max(ODrawbin));
        [yoff2d,xoff2d] = find(ODrawbin == amp2d);
        sigx2d=vertbin/8;
        sigy2d=horizbin/8;
        guessave=3; %using a 3x3 binned pixel area to determine scaling fraction
        guessleftup = sum(sum(ODrawbin(1:guessave,1:guessave)))/guessave^2;
        guessleftdn = sum(sum(ODrawbin(horizbin-guessave:horizbin,1:guessave)))/guessave^2;
        guessrightup = sum(sum(ODrawbin(1:guessave,vertbin-guessave:vertbin)))/guessave^2;
        guessrightdn = sum(sum(ODrawbin(horizbin-guessave:horizbin,vertbin-guessave:vertbin)))/guessave^2;
        offset2d=(guessleftup + guessleftdn + guessrightup + guessrightdn)/4 ;
        slopex2d=((guessrightup + guessrightdn) - (guessleftup + guessleftdn))/(2*horizbin);
        slopey2d=((guessleftdn + guessrightdn) - (guessrightup + guessleftup))/(2*vertbin);
        IniCondNR=[offset2d,amp2d,xoff2d,yoff2d,sigx2d,sigy2d,slopex2d,slopey2d];
        
        % Creating matrices for 2D fitting with ODrawbin
        xvecbin=1:vertbin;
        yvecbin=1:horizbin;
        Nptsbin=vertbin*horizbin;
        [xdatabin,ydatabin]=meshgrid(xvecbin,yvecbin);  % xdata(ydata) have columns=length(xvec), rows=length(yvec)
        % xdata copies xvec along its rows; ydata copies yvec along its columns
        error2d(1:Nptsbin)=1;   % DUMMY
        npoints(1:Nptsbin)=1;   % DUMMY - Each entry is the number of points
        fitcoordmatrix=[xdatabin(:),ydatabin(:),error2d(:),npoints(:)];
        Z2dbin=ODrawbin(:);  %flattened(1D) vector of ODrawbin
        
        % Fitting - data is treated with equal weight
        opts=statset('TolFun',1e-6);
        [P2dbin,r2dbin,J2dbin]=nlinfit(fitcoordmatrix,Z2dbin(:),@gauss2derror,IniCondNR,opts);
        P2d = [P2dbin(1),P2dbin(2),P2dbin(3)*bindim(2),P2dbin(4)*bindim(1),P2dbin(5)*bindim(2),P2dbin(6)*bindim(1),P2dbin(7)/bindim(2),P2dbin(8)/bindim(1)];
        
        % Generate OD plot based on fit parameters
        [horiz,vert] = size(ODraw);  % y-dir. is HORIZ. exper. dir.; x-dir. is VERT
        xvec=1:vert;
        yvec=1:horiz;
        Npts=vert*horiz;
        [xdata,ydata]=meshgrid(xvec,yvec);
        ploterrorod(1:Npts)=1;
        plotnpoints(1:Npts)=1;
        plotcoordmatrix=[xdata(:),ydata(:),ploterrorod(:),plotnpoints(:)];
        
        ODcalcvec=gauss2derror(P2d,plotcoordmatrix);    %OD calculated from fit paramters
        ODcalc = reshape(ODcalcvec, size(xdata));
        
        ODcalcbinvec=gauss2derror(P2dbin,fitcoordmatrix);    %ODbin calculated from fit paramters
        ODcalcbin = reshape(ODcalcbinvec, size(xdatabin));
        
        ODcalcICvec=gauss2derror(IniCondNR,fitcoordmatrix);   %OD based on initial conditions
        ODcalcIC = reshape(ODcalcICvec, size(xdatabin));
        
        ODresiduals = ODfilt-ODcalc;
        
        
        subplot(2,3,5)
        surf(ODcalcIC,'Marker','.')  %Plot 2d fit using IC
        %caxis(cax)
        colorbar
        shading flat
        grid off
        view(0,90);
        xlabel('vert binned')
        ylabel('horiz binned')
        title('OD (binned) from initial conditions')
        hold on
        
        subplot(2,3,2)
        surf(ODcalc,'Marker','.')  %Plot 2d fit using fit param
        caxis(cax)
        colorbar
        shading flat
        grid off
        view(0,90);
        xlabel('vert')
        ylabel('horiz')
        title('OD from 2d fit')
        hold on
        
        
        subplot(2,3,6)
        surf(ODcalcbin,'Marker','.')  %Plot 2d fit using binned fit param
        caxis('auto')
        view(0,90);
        colorbar
        shading flat
        grid off
        title('OD (binned) from 2d fit param.')
        xlabel('vert binned')
        ylabel('horiz binned')
        hold off
        
        subplot(2,3,3)
        surf(ODresiduals,'Marker','.')  %Plot 2d fit residuals
        caxis('auto')
        view(0,90);
        colorbar
        shading flat
        grid off
        title('True residues (ODfilt-ODcalc)')
        xlabel('vert')
        ylabel('horiz')
        hold off
    else
        P2d = [0,0,0,0,pX(3),pY(3),0,0];
    end
else
    P2d = [0,0,0,0,0,0,0,0];
end

% Give the width as the std deviation
if fit2d
    widthYm = (P2d(6))*expp.px_size*CCDbin/expp.mag;    %Y cloud size (m)
    widthXm = (P2d(5))*expp.px_size*CCDbin/expp.mag;    %X cloud size (m)
else
    widthYm = (pY(3))*expp.px_size*CCDbin/expp.mag;    %1D fits Y cloud size (m)
    widthXm = (pX(3))*expp.px_size*CCDbin/expp.mag;    %1D fits X cloud size (m)
end


if type_img == 1 % Fluorescence
    %     % Estimate number of atoms using camera
    %     capture_fraction = 0.5*(1 - sqrt(1 - (expp.na_telec)^2)); % fraction of total light captured by lens ( ~ 0.5 %)
    %     total_num_electrons = amp*sqrt(2*pi)*mean([pX(3) pY(3)]);
    %     total_photons = total_num_electrons/(expp.qe_std*expp.trans780*expp.trans_telec*capture_fraction);
    %     num_atoms = 2*total_photons/(img_time*cons.Gamma) % num_atoms = (num_photons/time) / (scattering rate)
    % Estimate number of atoms using camera
    if fit2d % if 2D fit has been done
        total_num_electrons = P2d(2)*2*pi*P2d(6)*P2d(5);
    else
        amp = (pX(1) + pY(1))/2 % Mean of 1D Gaussian fits
        total_num_electrons = amp*sqrt(2*pi)*mean([pX(3) pY(3)]);
    end
    total_photons = total_num_electrons/(expp.qe*expp.coll_eff);
    num_atoms = 2*total_photons/(img_time*2*pi*cons.Gamma) % num_atoms = (num_photons/time) / (scattering rate)
    set(handles.text_num_atoms,'string',['# Atoms: ' num2str(num_atoms,'%.2e')]);
elseif type_img == 3 % Absorption
    totalODraw = sum(sum(ODraw))*(expp.px_size*CCDbin/expp.mag)^2;
    num_atomsOD = totalODraw/AbsCross(0,0);
    if fit2d
        num_atomsFit = P2d(2)*2*pi*widthYm*widthXm/AbsCross(0,0);
    end
    set(handles.text_num_atoms,'string',['# Atoms (img): ' num2str(num_atomsOD,'%.2e')]);
    %set(handles.text_num_atomsFit2d,'string',['# Atoms (img): ' num2str(num_atomsFit,'%.2e')]);
end

% if type_img == 1 % Fluorescence
%     figure(1)
%     subplot(3,3,[1 2 4 5])
%     oneMat = ones(size(ODraw));
%     zeroMat = nan(size(ODraw));
%     zeroMat(yROI,xROI) = 1;
%     ODwindow = ODraw.*zeroMat;
%     imagesc(ODwindow);
% imagesc((ODfilt));
axes(handles.axes_processed)
imagesc(ODraw)
line([xROI(1) xROI(end)],[yROI(1) yROI(1)])
line([xROI(1) xROI(1)],[yROI(1) yROI(end)])
line([xROI(end) xROI(end)],[yROI(1) yROI(end)])
line([xROI(1) xROI(end)],[yROI(end) yROI(end)])
axis equal
xlims = xlim;
ylims = ylim;
set(gca,'FontSize',10)

% subplot(3,3,[3 6])
axes(handles.axes_y_proj)
plot(yInt,yROI,gauss(pY,yC),yC);
set(gca,'YDir','reverse');
ylim(ylims);
set(gca,'FontSize',10)

% subplot(3,3,[7 8])
axes(handles.axes_x_proj)
plot(xROI,xInt,xC,gauss(pX,xC));
xlim(xlims);
set(gca,'FontSize',10)

if type_img == 3 % Abs. img.
    axes(handles.axes_raw_abs_atoms)
    imagesc(rawimages(:,:,1))
    axis off
    
    axes(handles.axes_raw_abs_no_atoms)
    imagesc(rawimages(:,:,2))
    axis off
    
    axes(handles.axes_raw_background)
    imagesc(rawimages(:,:,3))
    axis off
else
    axes(handles.axes_raw_abs_atoms)
    imagesc(0)
    axis off
    
    axes(handles.axes_raw_abs_no_atoms)
    imagesc(0)
    axis off
    
    axes(handles.axes_raw_background)
    imagesc(0)
    axis off
end

set(handles.text_x_amplitude,'string',['X amp.: ' num2str(pX(1),'%.2e')]);
set(handles.text_y_amplitude,'string',['Y amp.: ' num2str(pY(1),'%.2e')]);
set(handles.text_x_width,'string',['X width: ' num2str(pX(3),'%.2e')]);
set(handles.text_y_width,'string',['Y width: ' num2str(pY(3),'%.2e')]);
set(handles.text_filename,'string',handles.dpath);
set(handles.text_peak_position,'string',['peak(v,h) = (' num2str(round(pX(2))) ',' num2str(round(pY(2))) ')']);
set(handles.text_roi,'string',['ROI(x,y) = (' num2str(xROI(1)) ',' num2str(xROI(end)) '),(' num2str(yROI(1)) ',' num2str(yROI(end)) ')']);

if type_img == 3
    set(handles.text_peak_pixel_count_signal,'string',['pk cnt(signal) = (' num2str(max(max(rawimages(:,:,1)))) ')']);
    set(handles.text_peak_pixel_count_bkgnd,'string',['pk cnt(bkgnd) = (' num2str(max(max(rawimages(:,:,2)))) ')']);
end

% try
%     h5create(hdfFilePath,'/dataAnalysis/numAtoms',size(num_atoms))
%     h5write(hdfFilePath,'/dataAnalysis/numAtoms',num_atoms)
% catch % Probable reason for failure is that the dataset already exists
%     h5write(hdfFilePath,'/dataAnalysis/numAtoms',num_atoms)
% end

% [vnames,xvars]=UpdatePlots(hdfFilePath)
% if ~isempty(xvars)
%     for i=1:length(xvars)
%         figure(500+i)
%         if type_img==1  %Fluorescence
%             subplot(2,1,1)
%             plot(xvars(i),num_atoms)
%             xlabel(vnames(i))
%             ylabel('atom number')
%             hold on
%             subplot(2,1,2)
%             plot(xvars(i),num2str(widthXm*cons.um),xvars(i),num2str(widthYm*cons.um))
%             xlabel(vnames(i))
%             ylabel('cloud size')
%             legend('sigma x','sigma y')
%             hold on
%         elseif type_img == 3 % Absorption
%             subplot(2,1,1)
%             plot(xvars(i),num_atomsOD,'.')
%             xlabel(vnames(i))
%             ylabel('atom number')
%             hold on
%             subplot(2,1,2)
%             plot(xvars(i),widthXm*cons.um,'+r',xvars(i),widthYm*cons.um,'<b')
%             xlabel(vnames(i))
%             ylabel('cloud size')
%             legend('sigma x','sigma y')
%             hold on
%         end
%     end
% end

%     h = subplot(3,3,9,'Visible', 'off');
%     cla(h);
%     text(0, .5, sprintf('%s\n%s\n%s\n%s', ...
%         ['v-width (um): ' num2str(widthXm*cons.um)], ['h-width (um): ' num2str(widthYm*cons.um)], ...
%         ['peak(v,h) = (' num2str(round(pX(2))) ',' num2str(round(pY(2))) ')'], ...
%         ['Na = ' num2str(num_atoms,'%e')]), ...
%         'VerticalAlignment', 'middle', ...
%         'FontName', 'Courier New', ...
%         'FontWeight', 'bold', ...
%         'FontSize', 12);

%     elseif type_img == 3 % Absorption
%     figure(1)
%     subplot(4,3,[1 2 4 5 ])
%     oneMat = ones(size(ODraw));
%     zeroMat = nan(size(ODraw));
%     zeroMat(yROI,xROI) = 1;
%     ODwindow = ODraw.*zeroMat;
%     imagesc(ODwindow);
%     % imagesc((ODfilt));
%     line([xROI(1) xROI(end)],[yROI(1) yROI(1)])
%     line([xROI(1) xROI(1)],[yROI(1) yROI(end)])
%     line([xROI(end) xROI(end)],[yROI(1) yROI(end)])
%     line([xROI(1) xROI(end)],[yROI(end) yROI(end)])
%     axis equal
%     xlims = xlim;
%     ylims = ylim;
%
%     subplot(4,3,[3 6])
%     plot(yInt,yROI,gauss(pY,yC),yC);
%     set(gca,'YDir','reverse');
%     ylim(ylims);
%
%     subplot(4,3,[7 8])
%     plot(xROI,xInt,xC,gauss(pX,xC));
%     xlim(xlims);
%
%     subplot(4,3,10)
%     imagesc(num')
%     axis equal
%
%     subplot(4,3,11)
%     imagesc(den')
%     axis equal
%
%     subplot(4,3,12)
%     imagesc(elec')
%     axis equal
%
%     h = subplot(4,3,9,'Visible', 'off');
%     cla(h);
%     text(0, .6, sprintf('%s\n%s\n%s\n%s\n%s\n%s \n%s \n%s \n%s', ...
%         ['v-width (um): ' num2str(widthXm*cons.um)], ['h-width (um): ' num2str(widthYm*cons.um)], ...
%         ['peak(v,h) = (' num2str(round(pX(2))) ',' num2str(round(pY(2))) ')'], ...
%         ['N(image) = ' num2str(num_atomsOD,'%e')], ...
%         ['N(fit) = ' num2str(num_atomsFit,'%e')], ...
%         ['peak pixel cnt = ' num2str(max(max(den)))], ...
%         ['Peak OD(image) = ' num2str(max(max(ODraw)))], ...
%         ['Peak OD(fit) = ' num2str(P2d(2))], ...
%         ['Mean OD(image) = ' num2str(mean(mean(ODraw)))]), ...
%         'VerticalAlignment', 'middle', ...
%         'FontName', 'Courier New', ...
%         'FontWeight', 'bold', ...
%         'FontSize', 12);
% end
